有兩隻程式一隻Servlet和資料庫做連線,一隻JSP負責產生html的table
1.Servlet
=== DataServlet.java ===
package demo;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DataServlet extends HttpServlet {
private ServletConfig config;
//Setting JSP page
String page="DataPage.jsp";
public void init(ServletConfig config)
throws ServletException{
this.config=config;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
PrintWriter out = response.getWriter();
//Establish connection to MySQL database
String connectionURL = "jdbc:mysql://localhost:3306/demopage";
Connection connection = null;
ResultSet rs;
response.setContentType("text/html");
List dataList = new ArrayList();
try {
// Load the database driver
Class.forName("com.mysql.jdbc.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection(connectionURL, "root", "qwerfdsa");
//Select the data from the database
String sql = "select * from company";
Statement s = connection.createStatement();
s.executeQuery (sql);
rs = s.getResultSet();
while (rs.next ()){
//Add records into data list
dataList.add(rs.getString("comid"));
dataList.add(rs.getString("comname"));
}
rs.close ();
s.close ();
}catch(Exception e){
System.out.println("Exception is ;"+e);
}
request.setAttribute("data",dataList);
//Disptching request
RequestDispatcher dispatcher = request.getRequestDispatcher(page);
if (dispatcher != null){
dispatcher.forward(request, response);
}
}
}
2.JSP
=== DataPage.jsp ===
<%@page language="java" import="java.util.*" %>
<title>Data Page</title>
<table border="1" width="303">
<tr>
<td width="119"><b>User ID</b></td>
<td width="168"><b>User Name</b></td>
</tr>
<%Iterator itr;%>
<% List data= (List)request.getAttribute("data");
for (itr=data.iterator(); itr.hasNext(); )
{
%>
<tr>
<td width="119"><%=itr.next()%></td>
<td width="168"><%=itr.next()%></td>
</tr>
<%}%>
</table>